import { defineStore } from 'pinia'
import { ref } from 'vue'
import { addOrderInfoAPI, getOrderInfoAPI, cancelOrderAPI, toGetOrderStatusAPI } from '@/api/order'
import { orderInfoType, responseOrderInfoType, orderStatusType, responseOrderStatusType } from '@/api/order/type'
import { membershipInformationAPI } from '@/api/auth'
import { UserInfoType, responseUserInfoType } from '@/api/auth/type'

export const useOrderStore = defineStore('order', () => {
  // 订单详情
  const orderInfo = ref({} as orderInfoType)
  // 订单状态
  const orderStatus = ref([] as orderStatusType[])
  // 会员个人信息
  const userInfo_plus = ref({} as UserInfoType)

  /**
   * 创建订单
   *
   * @param hoscode {string} 医院编号，限流使用
   * @param scheduleId {string} 排班id
   * @param patientId {string | number} 就诊人id
   */
  const addOrderInfo = async (hoscode: string, scheduleId: string, patientId: number | string) => {
    const { data: res } = await addOrderInfoAPI(hoscode, scheduleId, patientId)
    if (res.code !== 200) return ElMessage.error(res.message)
    return res.data
  }

  /**
   * 获取订单
   *
   * @param id {number} 订单id
   */
  const getOrderInfo = async (id: string | number) => {
    const { data: res }: responseOrderInfoType = await getOrderInfoAPI(id)
    if (res.code !== 200) return ElMessage.error(res.message)
    orderInfo.value = res.data
  }

  /**
   * 获取订单状态
   */
  const toGetOrderStatus = async () => {
    const { data: res }: responseOrderStatusType = await toGetOrderStatusAPI()
    if (res.code !== 200) return ElMessage.error(res.message)
    orderStatus.value = res.data
  }

  /**
   * 取消订单
   *
   * @param orderId {string | number}
   */
  const cancelOrder = async (orderId: string | number) => {
    const { data: res } = await cancelOrderAPI(orderId)
    if (res.code !== 200) return ElMessage.error(res.message)
    return res.data
  }

  /** 获取会员信息 */
  const membershipInformation = async () => {
    const { data: res }: responseUserInfoType = await membershipInformationAPI()
    if (res.code !== 200) return ElMessage.error(res.message)
    userInfo_plus.value = res.data
  }

  return {
    orderInfo,
    addOrderInfo,
    getOrderInfo,
    orderStatus,
    toGetOrderStatus,
    cancelOrder,
    userInfo_plus,
    membershipInformation,
  }
})
